package lab3;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class MyMain {

	public static void main(String args[]) {
		if(args.length!=2) {
			System.err.println("Количество входных параметров не верно");
			System.exit(0);
		}

		String path = args[0];
		int numOfThreads = Integer.parseInt(args[1]);

		ConcurrentHashMap<String, AtomicInteger> Words = new ConcurrentHashMap<String, AtomicInteger>();
		try {
			File input = new File(path);
			try (BufferedReader reader = new BufferedReader(
					new FileReader(input))) {

				String line;
				Vector<String> lines = new Vector<String>();
				while ((line = reader.readLine()) != null) {
					lines.add(line);
				}
				
				// lines.toArray(new String[0]);
				

				String[] allLines = new String[lines.size()];
				int t = 0;
				for (String oneLine : lines) {
					allLines[t] = oneLine;
					t++;
				}
				String[] fewLines = new String[3];
				ExecutorService executor = Executors
						.newFixedThreadPool(numOfThreads);

				for (int i = 0; i < allLines.length;) {
					int N;
					if (allLines.length - i >= 3) {
						N = 3;
					} else {
						N = allLines.length - i;
					}
					fewLines = new String[N];
					for (int j = 0; j < N; j++) {
						fewLines[j] = allLines[i + j];
					}
					i += N;

					executor.submit(new CountWordsThread(fewLines, Words));
				}
				executor.shutdown();
				//System.out.println("shutdown");
				while (!executor.awaitTermination(50L, TimeUnit.SECONDS))
					;

				//System.out.println("terminated");
				Set<Entry<String, AtomicInteger>> set = Words.entrySet();
				Iterator<Entry<String, AtomicInteger>> it = set.iterator();
				while (it.hasNext()) {

					Entry<String, AtomicInteger> me = it.next();

					
				//	if(me.getValue().get()>500){
					System.out.println(me.getKey() + " : " + me.getValue());
				//	}

				}
			} catch (FileNotFoundException e1) {
				System.err.println("Входной файл не найден");
				System.exit(0);
			} catch (InterruptedException e) {
				System.err.println("Тред был прерван " + e);
			}

		} catch (IOException e) {
			System.err.println("Не возможно закрыть файл " + e);
		}

	}
}